package com.zlsy.springbootdemo.mt.reward;

import com.zlsy.springbootdemo.mt.enums.UserEnums;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhouliang
 * @date 2021/1/22 15:14
 */
@Slf4j
@Component
public class FactorRewardStrategyFactory extends StrategyFactory
    implements ApplicationContextAware {
  private static final Map<Integer, RewardStrategy> map = new ConcurrentHashMap<>();
  private static ApplicationContext applicationContext;

  @Override
  public RewardStrategy createStrategy(Class c) {
    RewardStrategy product = null;
    try {
      product = (RewardStrategy) Class.forName(c.getName()).newInstance();
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }
    return product;
  }

  @Override
  @SuppressWarnings("unchecked")
  public RewardStrategy createStrategy(UserEnums enums) {
    Integer type = enums.getType();
    RewardStrategy rewardStrategy = map.get(type);
    if (Objects.isNull(rewardStrategy)) {
      Class c = enums.getC();
      rewardStrategy = (RewardStrategy) applicationContext.getBean(c);
      map.put(type, rewardStrategy);
    } else {
      return rewardStrategy;
    }
    return rewardStrategy;
  }

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    FactorRewardStrategyFactory.applicationContext = applicationContext;
  }
}
